import { useEffect, useState } from 'react';

interface Role {
    id: number;
    username: string;
    password: string; // 如果不需要在前端显示密码，可以考虑去掉
    permission: string;
}

const RolesPage: React.FC = () => {
    const [roles, setRoles] = useState<Role[]>([]);

    useEffect(() => {
        const fetchRoles = async () => {
            try {
                const response = await fetch('http://localhost:8000/roles');
                // console.log(response);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data: Role[] = await response.json();
                // console.log(data);
                setRoles(data);
            } catch (error) {
                console.error('Error fetching roles:', error);
            }
        };

        fetchRoles();
    }, []);

    const addRole = async () => {
        const newRole: Omit<Role, 'id'> = { username: 'newUser', password: 'newPassword', permission: 'user' };
        await fetch('http://localhost:8000/roles', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(newRole),
        });
        // 重新获取角色以更新列表
        const response = await fetch('http://localhost:8000/roles');
        const data: Role[] = await response.json();
        setRoles(data);
    };

    return (
        <div>
            <h1>Roles</h1>
            <ul>
                {roles.map(role => (
                    <li key={role.id}>{role.username} - {role.permission}</li>
                ))}
            </ul>
            <button onClick={addRole}>Add Role</button>
        </div>
    );
};

export default RolesPage; 